package department

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/dao"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
	"time"
)

//********************************************
//Func  ：查询所有部门列表
//Method：GET
//Usage ：
//********************************************
func QueryAllDepartments(c *gin.Context) {
	pageSize, err1 := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err1 != nil {
		global.Log.Error("QueryAllDepartments input param pagesize error:", zap.Any("error", err1))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	page, err2 := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err2 != nil {
		global.Log.Error("QueryAllDepartments input param page error:", zap.Any("error", err2))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	total, depts, err := dao.QueryDepartmentList(page, pageSize)
	if err != nil {
		global.Log.Error("QueryAllDepartments failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("查询部门失败"))
	} else {

		type OutputDepartment struct {
			DeptId     string
			DeptName   string    //部门名称（必填）
			Readme     string    //描述
			DeptHead   string    //部门负责人
			DeptHeadId string    //部门负责人ID
			CreatedAt  time.Time //创建部门时间
			Status     int       //状态
		}

		type DepartmentList struct { //列表查询输出
			Total int64
			List  []*OutputDepartment
		}

		output := &DepartmentList{
			Total: total,
		}
		for _, dept := range depts {
			var outputDept OutputDepartment
			outputDept.Status = dept.Status
			outputDept.CreatedAt = dept.CreatedAt
			outputDept.DeptId = strconv.FormatInt(dept.DeptId, 10)
			if dept.DeptHeadId > 0 {
				outputDept.DeptHeadId = strconv.FormatInt(dept.DeptHeadId, 10)
			}
			outputDept.DeptHead = dept.DeptHead
			outputDept.DeptName = dept.DeptName
			outputDept.Readme = dept.Readme
			output.List = append(output.List, &outputDept)
		}

		c.JSON(http.StatusOK, model.SuccessObject("操作成功", output))
		global.Log.Info("QueryAllDepartments success.", zap.Any("dept list", output))
	}
}

//********************************************
//Func  ：查询指定部门详情
//Method：GET
//Usage ：
//********************************************
func QueryDepartmentDetail(c *gin.Context) {
	deptId, err := strconv.ParseInt(c.DefaultQuery("deptId", ""), 10, 64)
	if err != nil {
		global.Log.Error("QueryDepartmentDetail deptid is lost.")
		c.JSON(http.StatusOK, model.Fail("未指明查询部门"))
		return
	}
	if deptId <= 0 {
		global.Log.Error("QueryDepartmentDetail deptid is lost.")
		c.JSON(http.StatusOK, model.Fail("未指明查询部门"))
		return
	}

	dept, err := dao.QueryDeptartmentDetail(deptId)
	if err != nil {
		global.Log.Error("QueryDepartmentDetail failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("查询部门详情失败"))
		return
	} else {
		if nil == dept {
			global.Log.Error("QueryDepartmentDetail failed.", zap.Any("error", err))
			c.JSON(http.StatusOK, model.Fail("查询部门详情失败"))
			return
		}
		type OutputDepartment struct {
			DeptId     string
			DeptName   string    //部门名称（必填）
			Readme     string    //描述
			DeptHead   string    //部门负责人
			DeptHeadId string    //部门负责人ID
			CreatedAt  time.Time //创建部门时间
			Status     int       //状态
		}
		var outputDept OutputDepartment
		outputDept.Status = dept.Status
		outputDept.CreatedAt = dept.CreatedAt
		outputDept.DeptId = strconv.FormatInt(dept.DeptId, 10)
		outputDept.DeptHeadId = strconv.FormatInt(dept.DeptHeadId, 10)
		outputDept.DeptHead = dept.DeptHead
		outputDept.Readme = dept.Readme

		c.JSON(http.StatusOK, model.SuccessObject("操作成功", dept))
		global.Log.Info("QueryDepartmentDetail success.", zap.Any("new step", outputDept))
	}
}

//********************************************
//Func  ：添加新部门(仅hr/超管可以访问)
//Method：POST
//Usage ：
//********************************************
func AddNewDepartment(c *gin.Context) {

	//todo. 此处需要判别当前请求发起者身份，如果非Hr，则驳回，无此操作权限
	requester := c.MustGet("USER").(*entity.Employee) //请求人
	if requester.Role != entity.EEmployeeRole_Hr {
		global.Log.Error("DeleteEmployee role not hr.")
		c.JSON(http.StatusOK, model.Fail("仅Hr才能进行部门配置"))
		return
	}

	var dept entity.Department
	var err error
	dept.DeptName = strings.TrimSpace(c.DefaultPostForm("deptName", "")) //标题
	if len(dept.DeptName) <= 0 {
		global.Log.Error("AddNewDepartment name is none.")
		c.JSON(http.StatusOK, model.Fail("部门名称不能为空"))
		return
	}

	dept.DeptHead = strings.TrimSpace(c.DefaultPostForm("deptHead", ""))
	dept.DeptHeadId, err = strconv.ParseInt(c.DefaultPostForm("deptHeadId", ""), 10, 64)
	dept.Readme = c.DefaultPostForm("readme", "")

	newdept, err := dao.CreateDepartment(dept)
	if err != nil {
		global.Log.Error("AddNewDepartment failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("添加部门失败"))
	} else {
		if nil == newdept {
			global.Log.Error("AddNewDepartment failed.", zap.Any("error", err))
			c.JSON(http.StatusOK, model.Fail("添加部门失败"))
			return
		}
		type OutputDepartment struct {
			DeptId     string
			DeptName   string    //部门名称（必填）
			Readme     string    //描述
			DeptHead   string    //部门负责人
			DeptHeadId string    //部门负责人ID
			CreatedAt  time.Time //创建部门时间
			Status     int       //状态
		}
		var outputDept OutputDepartment
		outputDept.Status = newdept.Status
		outputDept.CreatedAt = newdept.CreatedAt
		outputDept.DeptId = strconv.FormatInt(newdept.DeptId, 10)
		outputDept.DeptHeadId = strconv.FormatInt(newdept.DeptHeadId, 10)
		outputDept.DeptHead = newdept.DeptHead
		outputDept.Readme = newdept.Readme

		c.JSON(http.StatusOK, model.SuccessObject("添加部门成功", outputDept))
		global.Log.Info("AddNewDepartment success.", zap.Any("new step", newdept))
	}
}

//********************************************
//Func  ：更新部门信息
//Method：POST
//Usage ：
//********************************************
func UpdateDepartment(c *gin.Context) {

	//todo. 此处需要判别当前请求发起者身份，如果非Hr，则驳回，无此操作权限
	requester := c.MustGet("USER").(*entity.Employee) //请求人
	if requester.Role != entity.EEmployeeRole_Hr {
		global.Log.Error("DeleteEmployee role not hr.")
		c.JSON(http.StatusOK, model.Fail("仅Hr才能进行部门配置"))
		return
	}

	var dept entity.Department
	var err error
	dept.DeptName = strings.TrimSpace(c.DefaultPostForm("deptName", "")) //标题
	if len(dept.DeptName) <= 0 {
		global.Log.Error("UpdateDepartment name is none.")
		c.JSON(http.StatusOK, model.Fail("部门名称不能为空"))
		return
	}

	dept.DeptId, err = strconv.ParseInt(c.DefaultPostForm("deptId", ""), 10, 64)
	if err != nil {
		global.Log.Error("QueryDepartmentDetail deptid is lost.")
		c.JSON(http.StatusOK, model.Fail("更新部门信息失败"))
		return
	}

	if dept.DeptId <= 0 {
		global.Log.Error("UpdateDepartment name is none.")
		c.JSON(http.StatusOK, model.Fail("更新部门信息失败"))
		return
	}

	dept.DeptHead = c.DefaultPostForm("deptHead", "")
	dept.DeptHeadId, err = strconv.ParseInt(c.DefaultPostForm("deptHeadId", ""), 10, 64)
	dept.Readme = c.DefaultPostForm("readme", "")

	oldDept, err := dao.QueryDeptartmentDetail(dept.DeptId)
	if err == nil {
		if nil != oldDept {
			if dept.DeptHeadId != oldDept.DeptHeadId && oldDept.DeptHeadId > 0 {
				//部门主管ID有变更
				//那么原来部门人员的角色就要变了
			}
		}
	} else {
		global.Log.Error("UpdateDepartment get old dept info failed.")
	}

	err = dao.UpdateDepartment(dept, "")
	if err != nil {
		global.Log.Error("UpdateDepartment failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("更新部门失败"))
	} else {

		type OutputDepartment struct {
			DeptId     string
			DeptName   string    //部门名称（必填）
			Readme     string    //描述
			DeptHead   string    //部门负责人
			DeptHeadId string    //部门负责人ID
			CreatedAt  time.Time //创建部门时间
			Status     int       //状态
		}
		var outputDept OutputDepartment
		outputDept.Status = dept.Status
		outputDept.CreatedAt = dept.CreatedAt
		outputDept.DeptId = strconv.FormatInt(dept.DeptId, 10)
		outputDept.DeptHeadId = strconv.FormatInt(dept.DeptHeadId, 10)
		outputDept.DeptHead = dept.DeptHead
		outputDept.Readme = dept.Readme

		c.JSON(http.StatusOK, model.SuccessObject("操作成功", outputDept))
		global.Log.Info("UpdateDepartment success.", zap.Any("new step", dept))
	}
}

//********************************************
//Func  ：用户删除
//Method：DELETE
//Usage ：留言板页面-个人设置-账号注销
//********************************************
func DeleteDepartment(c *gin.Context) {

	//todo. 此处需要判别当前请求发起者身份，如果非Hr，则驳回，无此操作权限
	requester := c.MustGet("USER").(*entity.Employee) //请求人
	if requester.Role != entity.EEmployeeRole_Hr {
		global.Log.Error("DeleteEmployee role not hr.")
		c.JSON(http.StatusOK, model.Fail("仅Hr才能进行部门配置"))
		return
	}

	deptId, err := strconv.ParseInt(c.DefaultQuery("deptId", ""), 10, 64)
	if err != nil {
		global.Log.Error("DeleteDepartment deptid is lost.")
		c.JSON(http.StatusOK, model.Fail("删除部门失败"))
		return
	}

	err = dao.DeleteDepartment(deptId)
	if err != nil {
		global.Log.Error("DeleteDepartment failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("部门删除失败"))
	} else {
		c.JSON(http.StatusOK, model.Success("删除部门成功"))
		global.Log.Info("DeleteDepartment success.", zap.Any("delete deptId", deptId))
	}
}
